<?php
/**
 * Created by PhpStorm.
 * User: 68008000
 * Date: 2017/11/22
 * Time: 14:51
 */

namespace app\common\model;


use houdunwang\arr\Arr;
use think\Model;

/**
 * Class Category
 * @package app\common\model
 * 分类管理模型
 */
class Category extends Model
{
    //连接数据库
    protected $table= 'shop_category';
    protected $pk= 'cid';
    //树状分类数据
    //主页获取分类的数据
    public function CateData()
    {
        $data = db('category')->order('cid desc')->select();
        $treeData=Arr::tree($data,'cname','cid','pid');
        return $treeData;
    }
    //分类添加
    public function add($data){
        $res=$this->validate(true)->save($data);
       if(false == $res){
           return ['valid'=>0,'msg'=>$this->getError()];
       }else{
           return ['valid'=>1,'msg'=>'添加成功'];
       }
    }
    //分类编辑
    public function edit($data){
        $cid=input('param.cid');
        $res = $this->validate(true)->save($data,['cid' => $cid]);
        if(false === $res){
            // 验证失败 输出错误信息
            return ['valid'=>0,'msg'=>'修改失败'];
        }else{

            return ['valid'=>1,'msg'=>'修改成功'];
        }
    }
    public function getCateData($cid){
        $cids = $this->getSon(db('category')->select(),$cid);
        $cids[] = $cid;
        //此时已经获取了自己和自己的子级并删除
        $cateData = db('category')->whereNotIn('cid',$cids)->select();
        return Arr::tree($cateData,'cname');
    }

    //2.获取所有的子集
    public function getSon($data,$cid){

        static $temp = [];
        foreach ($data as $k=>$v){

            if($v['pid'] == $cid){
                $temp[] = $v['cid'];
                //递归
                $this->getSon($data,$v['cid']);
            }
        }
        return $temp;
    }
    //删除
    public function del($cid){
        //1.通过当前要删除的数据的cid获取当前数据的pid
        $pid = db('category')->where('cid',$cid)->value('pid');
        //2.修改子集的pid 改成父级的pid
        $this->where('pid',$cid)->update(['pid'=>$pid]);
        //3.删除当前这条数据
        $res = Category::destroy($cid);
        if ($res){
            return ['valid'=>1,'msg'=>'删除成功'];
        }else{
            return ['valid'=>0,'msg'=>'删除失败'];
        }
    }
}